package com.gw.quotes.activity;

import net.tsz.afinal.annotation.view.ViewInject;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;

import com.gw.quotes.AppInfo;
import com.gw.quotes.MyApplication;
import com.gw.quotes.R;
import com.gw.quotes.entity.system.User;
import com.gw.quotes.net.BaseServiceInter;
import com.gw.quotes.net.HttpCallBack;
import com.gw.quotes.net.Request;
import com.gw.quotes.net.Response;
import com.gw.quotes.net.service.UserLoginServiceImpl;
import com.gw.quotes.util.CommonTools;

public class SplashActivity extends BaseActivity {

	public static final String TAG = SplashActivity.class.getSimpleName();

	// @ViewInject(id=R.id.splash_loading_item)
	// private ImageView mSplashItem_iv = null;

	@ViewInject(id = R.id.splash_logo)
	private ImageView splashLogo = null;

	protected Handler mHandler = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		AppInfo.SCREEN_DENSITY = metrics.density;
		AppInfo.SCREEN_HEIGHT = metrics.heightPixels;
		AppInfo.SCREEN_WIDTH = metrics.widthPixels;

		mHandler = new Handler(getMainLooper());
		init();
	}

	private void init() {
		String logininfo = aCache.getAsString("logininfo");
		if (logininfo != null) {
			String[] infos = logininfo.split("\\|\\|");
			if (infos.length == 2) {
				login(infos[0], infos[1]);
				return;
			}
		}
		startActivity();
	}

	private void startActivity() {
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				Intent intent = new Intent(SplashActivity.this,
						MainActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.push_left_in,
						R.anim.push_left_out);
				SplashActivity.this.finish();
			}
		}, 1000);
	}

	public void login(String username, String password) {
		BaseServiceInter httpService = new UserLoginServiceImpl();
		Request request = new Request();
		request.setLoginname(username);
		request.setPassword(password);
		Response response = httpService.handler(request,
				new HttpCallBack<Response<User>>() {
					@Override
					public void onFinished(Response<User> response) {
						if (response.getResult() == Response.RESULT_SUCCESS) {
							// Toast.makeText(LoginActivity.this,response.getMsg(),Toast.LENGTH_SHORT).show();
							MyApplication.instance().setLoginUser(
									response.getObj());
						} else {
							CommonTools.showShortToast(SplashActivity.this,
									response.getMsg());
							// Toast.makeText(LoginActivity.this,response.getMsg(),Toast.LENGTH_SHORT).show();
						}
						startActivity();
					}
				});
	}
}
